/**
 * Environments 模块 API
 * 环境管理（分支）相关接口
 */

import { request, type ApiResponse, type RequestParamValue } from "../request";

// ============ 类型定义 ============

/**
 * 分支状态
 */
export type BranchStatus =
	| "CREATING_PROJECT"
	| "RUNNING_MIGRATIONS"
	| "MIGRATIONS_PASSED"
	| "MIGRATIONS_FAILED"
	| "FUNCTIONS_DEPLOYED"
	| "FUNCTIONS_FAILED";

/**
 * 预览项目状态
 */
export type PreviewProjectStatus =
	| "INACTIVE"
	| "ACTIVE_HEALTHY"
	| "ACTIVE_UNHEALTHY"
	| "COMING_UP"
	| "UNKNOWN"
	| "GOING_DOWN"
	| "INIT_FAILED"
	| "REMOVED"
	| "RESTORING"
	| "UPGRADING"
	| "PAUSING"
	| "RESTORE_FAILED"
	| "RESTARTING"
	| "PAUSE_FAILED"
	| "RESIZING";

/**
 * 运行步骤名称
 */
export type RunStepName = "clone" | "pull" | "health" | "configure" | "migrate" | "seed" | "deploy";

/**
 * 运行步骤状态
 */
export type RunStepStatus = "CREATED" | "DEAD" | "EXITED" | "PAUSED" | "REMOVING" | "RESTARTING" | "RUNNING";

/**
 * 实例大小
 */
export type InstanceSize =
	| "pico"
	| "nano"
	| "micro"
	| "small"
	| "medium"
	| "large"
	| "xlarge"
	| "2xlarge"
	| "4xlarge"
	| "8xlarge"
	| "12xlarge"
	| "16xlarge"
	| "24xlarge"
	| "24xlarge_optimized_memory"
	| "24xlarge_optimized_cpu"
	| "24xlarge_high_memory"
	| "48xlarge"
	| "48xlarge_optimized_memory"
	| "48xlarge_optimized_cpu"
	| "48xlarge_high_memory";

/**
 * 发布渠道
 */
export type ReleaseChannel = "internal" | "alpha" | "beta" | "ga" | "withdrawn" | "preview";

/**
 * Postgres 引擎版本
 */
export type PostgresEngine = "15" | "17" | "17-oriole";

/**
 * 分支响应
 */
export interface BranchResponse {
	id: string;
	name: string;
	project_ref: string;
	parent_project_ref: string;
	is_default: boolean;
	git_branch?: string;
	pr_number?: number;
	latest_check_run_id?: number;
	persistent: boolean;
	status: BranchStatus;
	created_at: string;
	updated_at: string;
	review_requested_at?: string;
	with_data: boolean;
	notify_url?: string;
	deletion_scheduled_at?: string;
	preview_project_status?: PreviewProjectStatus;
}

/**
 * 分支详情响应
 */
export interface BranchDetailResponse {
	ref: string;
	postgres_version: string;
	postgres_engine: string;
	release_channel: string;
	status: PreviewProjectStatus;
	db_host: string;
	db_port: number;
	db_user?: string;
	db_pass?: string;
	jwt_secret?: string;
}

/**
 * 创建分支请求体
 */
export interface CreateBranchBody {
	branch_name: string;
	git_branch?: string;
	is_default?: boolean;
	persistent?: boolean;
	region?: string;
	desired_instance_size?: InstanceSize;
	release_channel?: ReleaseChannel;
	postgres_engine?: PostgresEngine;
	secrets?: Record<string, string>;
	with_data?: boolean;
	notify_url?: string;
}

/**
 * 更新分支请求体
 */
export interface UpdateBranchBody {
	branch_name?: string;
	git_branch?: string;
	reset_on_push?: boolean;
	persistent?: boolean;
	status?: BranchStatus;
	request_review?: boolean;
	notify_url?: string;
}

/**
 * 分支操作请求体
 */
export interface BranchActionBody {
	migration_version?: string;
}

/**
 * 分支删除响应
 */
export interface BranchDeleteResponse {
	message: "ok";
}

/**
 * 分支更新响应
 */
export interface BranchUpdateResponse {
	workflow_run_id: string;
	message: "ok";
}

/**
 * 分支恢复响应
 */
export interface BranchRestoreResponse {
	message: "Branch restoration initiated";
}

/**
 * 运行步骤
 */
export interface RunStep {
	name: RunStepName;
	status: RunStepStatus;
	created_at: string;
	updated_at: string;
}

/**
 * Action Run 响应
 */
export interface ActionRunResponse {
	id: string;
	branch_id: string;
	run_steps: RunStep[];
	git_config: null;
	workdir: string | null;
	check_run_id: number | null;
	created_at: string;
	updated_at: string;
}

/**
 * 更新运行状态请求体
 */
export interface UpdateRunStatusBody {
	clone?: RunStepStatus;
	pull?: RunStepStatus;
	health?: RunStepStatus;
	configure?: RunStepStatus;
	migrate?: RunStepStatus;
	seed?: RunStepStatus;
	deploy?: RunStepStatus;
}

/**
 * 更新运行状态响应
 */
export interface UpdateRunStatusResponse {
	message: "ok";
}

// ============ API 方法 ============

/**
 * 获取数据库分支配置
 */
export function getBranchConfig(
	branchIdOrRef: string
): Promise<ApiResponse<BranchDetailResponse>> {
	return request.get<BranchDetailResponse>(
		`/v1/branches/${branchIdOrRef}`
	);
}

/**
 * 更新数据库分支配置
 */
export function updateBranchConfig(
	branchIdOrRef: string,
	data: UpdateBranchBody
): Promise<ApiResponse<BranchResponse>> {
	return request.patch<BranchResponse>(
		`/v1/branches/${branchIdOrRef}`,
		data
	);
}

/**
 * 删除数据库分支
 */
export function deleteBranch(
	branchIdOrRef: string,
	force?: boolean
): Promise<ApiResponse<BranchDeleteResponse>> {
	return request.delete<BranchDeleteResponse>(
		`/v1/branches/${branchIdOrRef}`,
		undefined,
		{ params: force !== undefined ? { force } : undefined }
	);
}

/**
 * 推送数据库分支
 */
export function pushBranch(
	branchIdOrRef: string,
	data?: BranchActionBody
): Promise<ApiResponse<BranchUpdateResponse>> {
	return request.post<BranchUpdateResponse>(
		`/v1/branches/${branchIdOrRef}/push`,
		data
	);
}

/**
 * 合并数据库分支
 */
export function mergeBranch(
	branchIdOrRef: string,
	data?: BranchActionBody
): Promise<ApiResponse<BranchUpdateResponse>> {
	return request.post<BranchUpdateResponse>(
		`/v1/branches/${branchIdOrRef}/merge`,
		data
	);
}

/**
 * 重置数据库分支
 */
export function resetBranch(
	branchIdOrRef: string,
	data?: BranchActionBody
): Promise<ApiResponse<BranchUpdateResponse>> {
	return request.post<BranchUpdateResponse>(
		`/v1/branches/${branchIdOrRef}/reset`,
		data
	);
}

/**
 * 恢复计划删除的分支
 */
export function restoreBranch(
	branchIdOrRef: string
): Promise<ApiResponse<BranchRestoreResponse>> {
	return request.post<BranchRestoreResponse>(
		`/v1/branches/${branchIdOrRef}/restore`
	);
}

/**
 * 获取分支差异（Beta）
 */
export function diffBranch(
	branchIdOrRef: string,
	includedSchemas?: string
): Promise<ApiResponse<string>> {
	return request.get<string>(
		`/v1/branches/${branchIdOrRef}/diff`,
		includedSchemas ? { included_schemas: includedSchemas } : undefined
	);
}

/**
 * 列出所有 Action Runs
 */
export function listActionRuns(
	ref: string,
	params?: { offset?: number; limit?: number }
): Promise<ApiResponse<ActionRunResponse[]>> {
	return request.get<ActionRunResponse[]>(
		`/v1/projects/${ref}/actions`,
		params as Record<string, RequestParamValue>
	);
}

/**
 * 获取 Action Run 状态
 */
export function getActionRun(
	ref: string,
	runId: string
): Promise<ApiResponse<ActionRunResponse>> {
	return request.get<ActionRunResponse>(
		`/v1/projects/${ref}/actions/${runId}`
	);
}

/**
 * 更新 Action Run 状态
 */
export function updateActionRunStatus(
	ref: string,
	runId: string,
	data: UpdateRunStatusBody
): Promise<ApiResponse<UpdateRunStatusResponse>> {
	return request.patch<UpdateRunStatusResponse>(
		`/v1/projects/${ref}/actions/${runId}/status`,
		data
	);
}

/**
 * 获取 Action Run 日志
 */
export function getActionRunLogs(
	ref: string,
	runId: string
): Promise<ApiResponse<string>> {
	return request.get<string>(
		`/v1/projects/${ref}/actions/${runId}/logs`
	);
}

/**
 * 列出所有数据库分支
 */
export function listBranches(
	ref: string
): Promise<ApiResponse<BranchResponse[]>> {
	return request.get<BranchResponse[]>(
		`/v1/projects/${ref}/branches`
	);
}

/**
 * 创建数据库分支
 */
export function createBranch(
	ref: string,
	data: CreateBranchBody
): Promise<ApiResponse<BranchResponse>> {
	return request.post<BranchResponse>(
		`/v1/projects/${ref}/branches`,
		data
	);
}

/**
 * 禁用预览分支
 */
export function disablePreviewBranching(
	ref: string
): Promise<ApiResponse<Record<string, unknown>>> {
	return request.delete<Record<string, unknown>>(
		`/v1/projects/${ref}/branches`
	);
}

/**
 * 按名称获取数据库分支
 */
export function getBranchByName(
	ref: string,
	name: string
): Promise<ApiResponse<BranchResponse>> {
	return request.get<BranchResponse>(
		`/v1/projects/${ref}/branches/${name}`
	);
}

export default {
	getBranchConfig,
	updateBranchConfig,
	deleteBranch,
	pushBranch,
	mergeBranch,
	resetBranch,
	restoreBranch,
	diffBranch,
	listActionRuns,
	getActionRun,
	updateActionRunStatus,
	getActionRunLogs,
	listBranches,
	createBranch,
	disablePreviewBranching,
	getBranchByName
};
